﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AccountRepository.cs" company="Concept Architecture">
//   (c) 2010 Muhammad Umer Farooq
// </copyright>
// <summary>
//   Defines the <seealso cref="Hisaab.Data.AccountRepository" /> type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hisaab.Data
{
    using System;
    using System.Data.Objects;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Linq.Expressions;
    using Common;
    using Entities;
    using Filters;
    using Interfaces;

    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// Defines the <seealso cref="Hisaab.Data.AccountRepository"/> type.
    /// </summary>
    public class AccountRepository : IAccountRepository
    {
        /// <summary>
        /// Databse instance to use
        /// </summary>
        private readonly IDatabase _database;

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountRepository"/> class.
        /// </summary>
        public AccountRepository()
            : this(ServiceLocator.Current.GetInstance<IDatabase>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountRepository"/> class.
        /// </summary>
        /// <param name="database">The database.</param>
        public AccountRepository(IDatabase database)
        {
            Contract.Requires<ArgumentNullException>(database != null);
            _database = database;
        }

        /// <summary>
        /// Gets the filtered.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of filtered items</returns>
        public IQueryable<Account> Query(Account filter, int? pageNo, int? pageSize)
        {
            return _database.Accounts
                .Filter(filter)
                .Page(pageNo, pageSize);
        }

        /// <summary>
        /// Queries the specified filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of filtered items</returns>
        public IQueryable<Account> Filter(Expression<Func<Account, bool>> filter, int? pageNo, int? pageSize)
        {
            return _database.Accounts
               .Where(filter)
               .Page(pageNo, pageSize);
        }

        /// <summary>
        /// Finds the by id.
        /// </summary>
        /// <param name="id">The id of entity</param>
        /// <returns>Entity matching by id</returns>
        public Account FindById(int id)
        {
            return _database.Accounts
                .Filter(new Account { Id = id })
                .FirstOrDefault();
        }

        /// <summary>
        /// Adds the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>Id of account added</returns>
        public int Add(Account entity)
        {
            _database.Accounts.AddObject(entity);
            _database.SaveChanges();
            _database.Refresh(RefreshMode.StoreWins, entity);
            return entity.Id;
        }

        /// <summary>
        /// Updates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Update(Account entity)
        {
            var previousEntity = _database.Accounts.Filter(new Account { Id = entity.Id }).FirstOrDefault();

            if (previousEntity != null)
            {
                previousEntity.Name = entity.Name;
                previousEntity.AccountType = entity.AccountType;
                previousEntity.AccountNumber = entity.AccountNumber;
            }

            _database.SaveChanges();
        }

        /// <summary>
        /// Deletes the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Delete(Account entity)
        {
            var previousEntity = _database.Accounts.Filter(new Account { Id = entity.Id }).FirstOrDefault();

            if (previousEntity != null)
            {
                _database.Accounts.DeleteObject(previousEntity);
            }

            _database.SaveChanges();
        }

        /// <summary>
        /// Gets the monthly balance summary.
        /// </summary>
        /// <param name="accountId">The account id.</param>
        /// <returns>
        /// List of month and balance
        /// </returns>
        public IQueryable<AccountMonthlyTotal> GetMonthlyBalanceSummary(int accountId)
        {
            return _database.Transactions
                .Where(x => x.Account == accountId)
                .GroupBy(x => new { x.Date.Year, x.Date.Month })
                .OrderBy(x => x.Key.Year).ThenBy(x => x.Key.Month)
                .Select(t => new AccountMonthlyTotal
                                 {
                                     Year = t.Key.Year,
                                     Month = t.Key.Month,
                                     MonthlyTotal = t.Sum(x => x.Amount),
                                 });
        }

        /// <summary>
        /// Gets the account totals.
        /// </summary>
        /// <param name="userId">The calling user id</param>
        /// <returns>List of account totals and summary</returns>
        public IQueryable<KeyValue<Account, decimal>> GetAccountTotals(int userId)
        {
            return _database.Accounts
                .Join(
                    _database.Transactions,
                    a => a.Id,
                    t => t.Account,
                    (a, t) => new { a, t })
                .OrderBy(o => o.t.Account)
                .GroupBy(g1 => g1.a, g2 => g2.t)
                .Where(w => w.Key.OwnerId == userId)
                .Select(
                    g =>
                    new KeyValue<Account, decimal>
                        {
                            Key = g.Key,
                            Value = g.Sum(z => z.Amount)
                        });
        }
    }
}